<?php
namespace Api;
use Kuyuan\WqCore\api\Api;
use Kuyuan\WqCore\cache\Cache;
use Kuyuan\WqCore\util\Util;
use Kuyuan\WqCore\wx\Message;

class Coupon extends Api
{
    private $Coupon = null;
    public function __construct()
    {
        parent::__construct();
        $this->Coupon = new \Controller\Coupon();
    }

    /**
     * 新增编辑卡券
     */
    public function edit()
    {
        Util::appointPost();
        if($_coupon_id = $this->Coupon->edit($this->_gpc["data"],$this->_gpc["coupon_id"])){
            if($this->testTplMessageNotice()) {
                $this->tplMessageNotice();
            }
            $_result = array("code"=>0,"data"=>$_coupon_id);
        } else {
            $_result = array("code"=>103);
        }
        Util::returns($_result);
    }

    /**
     * 检测是否模板消息通知，防止短时间内频繁模板消息通知
     */
    private function testTplMessageNotice()
    {
        global $_W;
        $_cache_name = KUYUAN_NAME.$_W["account"]["uniacid"]."coupon_await_check_tpl";
        if(Cache::name($_cache_name)) return false;
        Cache::name($_cache_name,KUYUAN_NAME,60);
        return true;
    }

    /**
     * 检测发送模板消息通知管理员审核素材
     * @param $_result
     */
    private function tplMessageNotice()
    {
        // 1、检测系统是否开启了审核功能
        $Setting = $this->newController("Setting");
        $_setting = $Setting->find();
        if ($_setting["coupon_check"]) {
            // 3 、获取管理员列表
            $Manage = $this->newController("Manage");
            $_manage_list = $Manage->getList();
            if(count($_manage_list) > 0) {
                // 4.1、判断有没有设置模板消息id
                $SettingMessage = $this->newController("SettingMessage");
                $_setting_message = $SettingMessage->find();
                $_tpl_id = $_setting_message["await_check_tpl"];
                $Member = $this->newController("Member");
                $_member = $Member->findNameHeader();
                load()->func('communication');
                foreach($_manage_list as $_v) {
                    $_tpl_result = Message::sendTpl(
                        $Member->uidToOpenid($_v["uid"]),
                        $_tpl_id,
                        array(
                            "first" => array(
                                "value" => $_setting["app_name"]."待审核通知"
                            ),
                            "keyword1" => array(
                                "value" => "用户卡券审核"
                            ),
                            "keyword2" => array(
                                "value" => $_member["nickname"]
                            ),
                            "keyword3" => array(
                                "value" => date("Y-m-d H:i:s")
                            ),
                            "remark" => array(
                                "value" => "请登录后台处理卡券审核"
                            )
                        )
                    );
                    if(!$_tpl_result) {
                        @ihttp_email(
                            $_v["email"],
                            $_setting["app_name"]."待审核通知",
                            array(
                                "<p>类型：用户卡券审核</p><p>卡券所属用户：".$_member["nickname"]."</p><p>上传时间：".date("Y-m-d H:i:s")."</p><p>请登录后台处理卡券审核</p>"
                            )
                        );
                    }
                }
            }
        }
    }

    /**
     * 获取用户卡券列表
     */
    public function getUserAll()
    {
        Util::appointGet();
        $_list = $this->Coupon->getUserAll(
            $this->_gpc["limit"],
            0,
            $this->_gpc["type"]
        );
        if(count($_list) > 0){
            $_result = array("code"=>0,"data"=>$_list);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * 获取一个卡券详情
     */
    public function get()
    {
        Util::appointGet();
        $_data = $this->Coupon->get($this->_gpc["coupon_id"]);
        if($_data) {
            $_result = array("code"=>0,"data"=>$_data);
        } else {
            $_result = array("code"=>100,"data"=>$_data);
        }
        Util::returns($_result);
    }

    /**
     * 获取一个卡券id获取原生数据
     */
    public function take()
    {
        Util::appointGet();
        $_data = $this->Coupon->take($this->_gpc["coupon_id"]);
        if($_data) {
            $_result = array("code"=>0,"data"=>$_data);
        } else {
            $_result = array("code"=>100,"data"=>$_data);
        }
        Util::returns($_result);
    }

    /**
     * 删除卡券
     */
    public function del()
    {
        Util::appointPost();
        if($this->Coupon->del($this->_gpc["coupon_id"])) {
            $_result = array("code"=>0);
        } else {
            $_result = array("code"=>102);
        }
        Util::returns($_result);
    }

    /**
     * 获取需要审核的卡券列表
     */
    public function getCheckList()
    {
        Util::appointGet();
        $_data = $this->Coupon->getCheckList($this->_gpc["limit"]);
        if($_data){
            $_result = array("code"=>0,"data"=>$_data);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * 获取需要审核卡券总数
     */
    public function getCheckTotal()
    {
        Util::appointGet();
        Util::returns(array("code"=>0,"data"=>$this->Coupon->getCheckTotal()));
    }

    /**
     * 修改卡券状态
     */
    public function changeStatus()
    {
        Util::appointPost();
        if($this->Coupon->edit(array("status"=>$this->_gpc["status"]),$this->_gpc["coupon_id"],$this->_gpc["source"] != 'manage_check')) {
            if($this->_gpc["status"] == 1) {
                $this->sendMessage(true);
            } else if($this->_gpc["status"] == 3) {
                $this->sendMessage(false);
            } else {
                $this->sendMessage(false);
            }
            $_result = array("code"=>0);
        } else {
            $_result = array("code"=>103);
        }
        Util::returns($_result);
    }

    /**
     * 发送审核消息消息通知
     * @param bool $_pass
     */
    private function sendMessage($_pass = true)
    {
        if(isset($this->_gpc["source"]) && $this->_gpc["source"] == 'manage_check') {
            $_remark = $this->_gpc["remark"];
            if(!$_pass) {
                if($this->_gpc["status"] == 9) {
                    $_remark = "卡券已被删除，" . $_remark;
                }
            } else {
                $_remark = '无';
            }
            $_params = array_merge(
                $this->getMessageParams(),
                array(
                    "pass" => $_pass,
                    "remark" => $_remark
                )
            );
            $_tel_message_result = $this->sendTplMessage($_params);
            if(!$_tel_message_result) {
                $this->sendSubscribeMessage($_params);
            }
        }
    }

    /**
     * 获取发送模板消息参数组
     * @param int $_uid 用户id
     * @return mixed
     */
    private function getMessageParams($_uid = 0)
    {
        $Member = $this->newController("Member");
        $_openid = $Member->uidToOpenid($_uid ? $_uid : $this->Coupon->value("uid",$this->_gpc["coupon_id"]));
        $SettingMessage = $this->newController("SettingMessage");
        $_setting_message = $SettingMessage->find();
        $Setting = $this->newController("Setting");
        $_setting = $Setting->find();
        return array(
            "openid" => $_openid,
            "templates" => $_setting_message,
            "app_name" => $_setting["app_name"],
        );
    }

    /**
     * 发送审核状态消息，模板消息
     * @param array $_params 参数数组
     * @params string $_openid 用户的openid
     * @params string $_template_id 模板消息id
     * @params string $_app_name 网站名字
     * @params bool $_pass 审核是否成功
     * @params string $_remark 审核失败后的备注消息
     * @return bool|mixed
     */
    private function sendTplMessage(Array $_params)
    {
        if(empty($_params["templates"]["result_check_tpl"])) return false;
        // 模板消息内容
        $_send_data = array(
            "first" => array(
                "value" => $_params["app_name"]."-卡券审核结果"
            ),
            "keyword1" => array(
                "value" => "管理员"
            ),
            "keyword2" => array(
                "value" => $_params["pass"] ? "审核通过" : "审核未通过"
            ),
            "keyword3" => array(
                "value" => date("Y-m-d H:i:s")
            ),
            "remark" => array(
                "value" => $_params["remark"]
            )
        );
        return Message::sendTpl(
            $_params["openid"],
            $_params["templates"]["result_check_tpl"],
            $_send_data,
            murl('entry//mobile',array('m'=>'kuyuan_hb'),true,true)."#/member"
        );
    }

    /**
     * 发送审核状态消息，发送订阅消息
     * @param array $_params 参数
     * @params string $_openid 用户openid
     * @params string $_template_id 模板消息id
     * @params bool $_pass 是否通过审核
     * @params string $_remark 备注消息
     * @return mixed
     */
    private function sendSubscribeMessage(Array $_params)
    {
        if(empty($_params["templates"]["result_check_sub"])) return false;
        $_send_data = array(
            "thing10" => array(
                "value" => $_params["app_name"]."-卡券审核结果"
            ),
            "phrase8" => array(
                "value" => $_params["pass"] ? "审核通过" : "审核未通过"
            ),
            "thing4" => array(
                "value" => $_params["remark"]
            ),
            "time9" => array(
                "value" => date("Y-m-d H:i:s")
            )
        );
        return Message::sendSubscribeMessage(
            $_params["openid"],
            $_params["templates"]["result_check_sub"],
            $_send_data,
            murl('entry//mobile',array('m'=>'kuyuan_hb'),true,true)."#/member"
        );
    }
}